//引入cheerio
import Cheerio from "cheerio";
import http from "http";
import fs from "fs";
import { v4 as uuidv4 } from "uuid";
import axios from "axios";
import { StringDecoder } from "string_decoder";
import { getRandomId } from "./common/index.js";
import SDTime from "silly-datetime"; //时间格式化处理插件
const decoder = new StringDecoder("utf-8"); //解析器，将buffer以utf-8编码方式解析
import { query, query2 } from "./mysqlQuery.js";
var reg = /\/.+\//g;
if (!fs.existsSync("./public")) {
  fs.mkdirSync("./public");
  console.log("文件夹创建成功");
}
//+Sync同步创建文件夹novelImage
if (!fs.existsSync("./public/novelImage")) {
  fs.mkdirSync("./public/novelImage");
  console.log("文件夹创建成功");
}
//获取整个dom对象,就是将dom结构转成可操作的jquery数据对象
// function getCurrentHtmlDom(html) {
//   //html地址或者html元素结构都型，nodejs版jquery,可以用jQuery的API来操作DOM。
//   const $ = Cheerio.load(html, {
//     decodeEntities: false, //防止.html()方法将里面的中文被编码
//   });
//   return $;
// }
//请求获取别人的html数据
function getOtherHtmlData(url) {
  //promise封装成同步代码
  return new Promise((resolve, reject) => {
    var html = "";
    http.get(url, (req, res) => {
      req.on("data", (data) => {
        html += data;
      });
      req.on("end", () => {
        const $ = Cheerio.load(html, {
          decodeEntities: false, //防止.html()方法将里面的中文被编码
        });
        resolve($); //返回这个html的dom
      });
    });
  }).catch((err) => {
    console.log(err);
  });
}
//保存小说txt
function createOneNovel2(src, id, distName) {
  return new Promise(async (resolve, reject) => {
    //src:下载文件地址，id:目录名，distName:小说名
    console.log(id, "--------", distName, "------", src);
    const res = await axios.get(src);
    if (!fs.existsSync("./public/novelTxt/" + id)) {
      fs.mkdirSync("./public/novelTxt/" + id);
      console.log("文件夹创建成功");
    }
    fs.writeFile(
      "./public/novelTxt/" + id + "/" + distName + ".txt",
      res.data,
      "utf-8",
      (err) => {
        if (err) {
          fs.rmdirSync("./public/novelTxt/" + id);
        } else {
          resolve();
        }
      }
    );
  });
}
function BlobToSaveImg() {
  //blob转img文件
  query([
    {
      sql: "select * from app_novel",
      values: [],
    },
  ])
    .then(async (res) => {
      let i = 0;
      while (i < res[0].rows.length) {
        try {
          let image_id = uuidv4().replace(/-/g, "");
          let fileSrc = `/novelImage/${image_id}.png`;
          fs.writeFileSync("./public" + fileSrc, res[0].rows[i].pic);
          let result = await query([{
            sql: "update app_novel set imgUrl=? where novel_id=?",
            values: [fileSrc, res[0].rows[i].novel_id],
          }]);
          console.log("保存文件成功");
        } catch (error) {
          console.log("保存文件失败！");
        }
        i++;
      }
    })
    .catch((err) => {
      console.log("报错喽");
    });
}
// BlobToSaveImg();
function addMysql() {
  return new Promise((reslove, reject) => {
    let chapter_id = uuidv4().replace(/-/g, "");
    query([
      {
        sql: "insert into app_novel_chapter (novel_id,title,chapterContent,chapter_id,word,sort,create_time,update_time) values (?,?,?,?,?,?,?,?)",
        values: [
          novel_id,
          title,
          chapterContent,
          chapter_id,
          chapterContent.length,
          i,
          SDTime.format(new Date(), "YYYY-MM-DD HH:mm:ss"),
          SDTime.format(new Date(), "YYYY-MM-DD HH:mm:ss"),
        ],
      },
    ])
      .then((res) => {
        reslove(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
function parentNovel(novel_id, findObject, txtObeject, pd, total) {
  return new Promise((reslove, reject) => {
    query([
      {
        sql: "insert into app_novel (novel_id,category,title,author,pic,content,word,create_time,update_time,hits_time) values (?,?,?,?,?,?,?,?,?,?)",
        values: [
          novel_id,
          findObject.classify_id,
          txtObeject.substring(0, txtObeject.lastIndexOf(".txt")),
          findObject.author,
          pd,
          findObject.descrie,
          total,
          SDTime.format(new Date(), "YYYY-MM-DD HH:mm:ss"),
          SDTime.format(new Date(), "YYYY-MM-DD HH:mm:ss"),
          SDTime.format(new Date(), "YYYY-MM-DD HH:mm:ss"),
        ],
      },
    ])
      .then((res) => {
        reslove(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
// putTxtSql()
//玄幻第一页
let xuanhuanList = [];
let classifyArr = [
  {
    id: 10001,
    text: "奇幻玄幻",
  },
  {
    id: 10002,
    text: "武侠仙侠",
  },
  {
    id: 10003,
    text: "历史军事",
  },
  {
    id: 10004,
    text: "都是娱乐",
  },
  {
    id: 10005,
    text: "竞技同人",
  },
  {
    id: 10006,
    text: "科幻游戏",
  },
  {
    id: 10007,
    text: "悬疑灵异",
  },
  {
    id: 10008,
    text: "评论文集",
  },
  {
    id: 10009,
    text: "其他",
  },
  {
    id: 10010,
    text: "言情小说",
  },
  {
    id: 10011,
    text: "网游",
  },
  {
    id: 10012,
    text: "女生",
  },
];
let currentIndex = 1; //默认奇幻玄幻
getOtherHtmlData("http://www.ibooktxt.org/html/xianxiaxiuzhen/3/").then(
  async (res) => {
    // console.log(res)
    return;
    res(".hotcontent:eq(1) .item").each((index, ele) => {
      xuanhuanList.push({
        detailSrc:
          "http://www.ibooktxt.org" +
          res(`.hotcontent:eq(1) .item:eq(${index}) .image`)
            .html()
            .match(reg)[0],
        bookName: res(`.hotcontent:eq(1) .item:eq(${index}) dl dt a`).html(),
        author: res(`.hotcontent:eq(1) .item:eq(${index}) .btm a`).html(),
        number: res(`.hotcontent:eq(1) .item:eq(${index}) .btm em`).html(),
        pictureSrc:
          res(`.hotcontent:eq(1) .item:eq(${index}) .image a img`)["0"].attribs[
            "data-original"
          ] == "/static/ibooktxt/nocover.jpg"
            ? "http://www.ibooktxt.org/static/ibooktxt/nocover.jpg"
            : res(`.hotcontent:eq(1) .item:eq(${index}) .image a img`)["0"]
                .attribs["data-original"],
        contentSrc: "",
        describe: res(`.hotcontent:eq(1) .item:eq(${index}) dl dd`).text(),
      });
    });
    // console.log(xuanhuanList);
    // return;
    let i = 0;
    let flag = true;
    let timer = null;
    timer = setInterval(async () => {
      if (i >= xuanhuanList.length) {
        clearInterval(timer);
        timer = null;
      } else {
        console.log("--------------------");
        if (flag) {
          flag = false;
          let fileNameId = getRandomId(8);
          console.log(fileNameId);
          try {
            const result = await getOtherHtmlData(xuanhuanList[i].detailSrc);
            let c = result("#maininfo .readbtn a:eq(2)")["0"].attribs.href;
            let arr = c.split("=");
            arr[arr.length - 1] = encodeURIComponent(arr[arr.length - 1]);
            let k = arr.join("=");
            xuanhuanList[i].contentSrc = "http://www.ibooktxt.org" + k;
            // console.log(result("#maininfo .readbtn a:eq(2)")["0"].attribs.href)
            // console.log(xuanhuanList[i].pictureSrc)
            // return

            const resHbh = await query([
              {
                sql: "insert into txtnovellist (fileNameId,bookName,author,total,createTime,classify_id) values (?,?,?,?,?,?);",
                values: [
                  fileNameId,
                  xuanhuanList[i].bookName,
                  xuanhuanList[i].author,
                  xuanhuanList[i].number,
                  // `data:image/jpg;base64,${pd}`,
                  // hr,
                  SDTime.format(new Date(), "YYYY-MM-DD HH:mm:ss"),
                  classifyArr[currentIndex].id,
                ],
              },
            ]);
            const mhbh = await createOneNovel(
              xuanhuanList[i].pictureSrc,
              fileNameId,
              xuanhuanList[i].describe
            );
            console.log(mhbh.id);
            const md = await createOneNovel2(
              xuanhuanList[i].contentSrc,
              mhbh.id,
              xuanhuanList[i].bookName
            );
            console.log(md);
          } catch (error) {
            console.log(error);
          }
          i++;
          flag = true;
        } else {
          console.log(i + "还在等待结果！");
        }
      }
    }, 1000);
  }
);
